
<template>
  <div class="project-detail">
    <el-tabs v-model="activeTab">
      <el-tab-pane label="需求管理" name="requirements">
        <div class="requirements-section">
          <div class="section-header">
            <h3>需求列表</h3>
            <el-button type="primary" size="small" @click="showCreateRequirementDialog = true">
              <el-icon><Plus /></el-icon>
              新增需求
            </el-button>
          </div>
          
          <el-table :data="requirements" style="width: 100%" v-loading="loading">
            <el-table-column prop="title" label="需求标题" min-width="200" />
            <el-table-column prop="description" label="描述" min-width="300" show-overflow-tooltip />
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="{ row }">
                <el-tag :type="getPriorityType(row.priority)" size="small">
                  {{ getPriorityText(row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">
                  {{ getStatusText(row.status) }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="editRequirement(row)">
                  <el-icon><Edit /></el-icon>
                  编辑
                </el-button>
                <el-button type="danger" size="small" @click="deleteRequirement(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
      
      <el-tab-pane label="文档管理" name="documents">
        <div class="documents-section">
          <div class="section-header">
            <h3>文档列表</h3>
            <el-upload
              ref="uploadRef"
              action="#"
              :http-request="uploadDocument"
              :before-upload="beforeUpload"
              :show-file-list="false"
              :data="{ documentType: uploadDocumentType }"
            >
              <template #trigger>
                <el-button type="primary" size="small">
                  <el-icon><Upload /></el-icon>
                  上传文档
                </el-button>
              </template>
            </el-upload>
          </div>
          
          <el-radio-group v-model="uploadDocumentType" size="small" style="margin-bottom: 20px;">
            <el-radio-button label="requirement">需求文档</el-radio-button>
            <el-radio-button label="technical">技术文档</el-radio-button>
          </el-radio-group>
          
          <el-table :data="documents" style="width: 100%" v-loading="docLoading">
            <el-table-column prop="original_name" label="文件名" min-width="250" />
            <el-table-column prop="document_type" label="文档类型" width="120">
              <template #default="{ row }">
                <el-tag :type="row.document_type === 'requirement' ? 'primary' : 'success'" size="small">
                  {{ row.document_type === 'requirement' ? '需求文档' : '技术文档' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="file_size" label="文件大小" width="120">
              <template #default="{ row }">
                {{ formatFileSize(row.file_size) }}
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="上传时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="200" fixed="right">
              <template #default="{ row }">
                <el-button type="primary" size="small" @click="downloadDocument(row)">
                  <el-icon><Download /></el-icon>
                  下载
                </el-button>
                <el-button type="danger" size="small" @click="deleteDocument(row)">
                  <el-icon><Delete /></el-icon>
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-tab-pane>
    </el-tabs>

    <!-- 创建/编辑需求对话框 -->
    <el-dialog
      v-model="showCreateRequirementDialog"
      :title="editingRequirement ? '编辑需求' : '新增需求'"
      width="600px"
    >
      <el-form :model="requirementForm" label-width="80px">
        <el-form-item label="需求标题">
          <el-input v-model="requirementForm.title" placeholder="请输入需求标题" />
        </el-form-item>
        <el-form-item label="需求描述">
          <el-input
            v-model="requirementForm.description"
            type="textarea"
            :rows="4"
            placeholder="请输入需求描述"
          />
        </el-form-item>
        <el-form-item label="优先级">
          <el-select v-model="requirementForm.priority" placeholder="请选择优先级">
            <el-option label="高" value="high" />
            <el-option label="中" value="medium" />
            <el-option label="低" value="low" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="requirementForm.status" placeholder="请选择状态">
            <el-option label="待处理" value="pending" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showCreateRequirementDialog = false">取消</el-button>
        <el-button type="primary" @click="saveRequirement">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'

export default {
  name: 'ProjectDetail',
  props: {
    project: {
      type: Object,
      required: true
    }
  },
  emits: ['close', 'refresh'],
  setup(props) {
    const activeTab = ref('requirements')
    const requirements = ref([])
    const documents = ref([])
    const loading = ref(false)
    const docLoading = ref(false)
    const showCreateRequirementDialog = ref(false)
    const editingRequirement = ref(null)
    const uploadDocumentType = ref('requirement')
    const uploadRef = ref(null)

    const requirementForm = reactive({
      title: '',
      description: '',
      priority: 'medium',
      status: 'pending'
    })

    // 加载需求列表
    const loadRequirements = async () => {
      loading.value = true
      try {
        const response = await axios.get(`/api/projects/${props.project.id}/requirements`)
        requirements.value = response.data
      } catch (error) {
        ElMessage.error('加载需求列表失败')
        console.error(error)
      } finally {
        loading.value = false
      }
    }

    // 加载文档列表
    const loadDocuments = async () => {
      docLoading.value = true
      try {
        const response = await axios.get(`/api/projects/${props.project.id}/documents`)
        documents.value = response.data
      } catch (error) {
        ElMessage.error('加载文档列表失败')
        console.error(error)
      } finally {
        docLoading.value = false
      }
    }

    // 获取优先级标签类型
    const getPriorityType = (priority) => {
      const typeMap = {
        high: 'danger',
        medium: 'warning',
        low: 'info'
      }
      return typeMap[priority] || 'info'
    }

    // 获取优先级文本
    const getPriorityText = (priority) => {
      const textMap = {
        high: '高',
        medium: '中',
        low: '低'
      }
      return textMap[priority] || priority
    }

    // 获取状态标签类型
    const getStatusType = (status) => {
      const typeMap = {
        pending: 'info',
        in_progress: 'warning',
        completed: 'success',
        cancelled: 'danger'
      }
      return typeMap[status] || 'info'
    }

    // 获取状态文本
    const getStatusText = (status) => {
      const textMap = {
        pending: '待处理',
        in_progress: '进行中',
        completed: '已完成',
        cancelled: '已取消'
      }
      return textMap[status] || status
    }

    // 格式化日期
    const formatDate = (dateString) => {
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }

    // 格式化文件大小
    const formatFileSize = (bytes) => {
      if (bytes === 0) return '0 B'
      const k = 1024
      const sizes = ['B', 'KB', 'MB', 'GB']
      const i = Math.floor(Math.log(bytes) / Math.log(k))
      return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
    }

    // 保存需求
    const saveRequirement = async () => {
      if (!requirementForm.title.trim()) {
        ElMessage.warning('请输入需求标题')
        return
      }

      try {
        if (editingRequirement.value) {
          // 编辑需求
          await axios.put(`/api/requirements/${editingRequirement.value.id}`, requirementForm)
          ElMessage.success('需求更新成功')
        } else {
          // 创建需求
          await axios.post(`/api/projects/${props.project.id}/requirements`, requirementForm)
          ElMessage.success('需求创建成功')
        }
        
        showCreateRequirementDialog.value = false
        resetRequirementForm()
        loadRequirements()
      } catch (error) {
        ElMessage.error(editingRequirement.value ? '更新需求失败' : '创建需求失败')
        console.error(error)
      }
    }

    // 编辑需求
    const editRequirement = (requirement) => {
      editingRequirement.value = requirement
      requirementForm.title = requirement.title
      requirementForm.description = requirement.description
      requirementForm.priority = requirement.priority
      requirementForm.status = requirement.status
      showCreateRequirementDialog.value = true
    }

    // 删除需求
    const deleteRequirement = async (requirement) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除需求 "${requirement.title}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await axios.delete(`/api/requirements/${requirement.id}`)
        ElMessage.success('需求删除成功')
        loadRequirements()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除需求失败')
          console.error(error)
        }
      }
    }

    // 重置需求表单
    const resetRequirementForm = () => {
      requirementForm.title = ''
      requirementForm.description = ''
      requirementForm.priority = 'medium'
      requirementForm.status = 'pending'
      editingRequirement.value = null
    }

    // 上传文档前的检查
    const beforeUpload = (file) => {
      const allowedTypes = ['.pdf', '.docx', '.md', '.txt']
      const fileExt = file.name.substring(file.name.lastIndexOf('.')).toLowerCase()
      
      if (!allowedTypes.includes(fileExt)) {
        ElMessage.error('仅支持上传 PDF、DOCX、MD、TXT 格式的文件')
        return false
      }
      
      if (file.size > 10 * 1024 * 1024) {
        ElMessage.error('文件大小不能超过 10MB')
        return false
      }
      
      return true
    }

    // 上传文档
    const uploadDocument = async (options) => {
      const formData = new FormData()
      formData.append('file', options.file)
      formData.append('documentType', uploadDocumentType.value)

      try {
        await axios.post(`/api/projects/${props.project.id}/documents`, formData, {
          headers: {
            'Content-Type': 'multipart/form-data'
          }
        })
        ElMessage.success('文档上传成功')
        loadDocuments()
      } catch (error) {
        ElMessage.error('文档上传失败')
        console.error(error)
      }
    }

    // 下载文档
    const downloadDocument = (document) => {
      window.open(`/api/documents/${document.id}/download`, '_blank')
    }

    // 删除文档
    const deleteDocument = async (document) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除文档 "${document.original_name}" 吗？`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }
        )

        await axios.delete(`/api/documents/${document.id}`)
        ElMessage.success('文档删除成功')
        loadDocuments()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除文档失败')
          console.error(error)
        }
      }
    }

    // 监听对话框关闭
    const handleDialogClose = () => {
      resetRequirementForm()
    }

    onMounted(() => {
      loadRequirements()
      loadDocuments()
    })

    return {
      activeTab,
      requirements,
      documents,
      loading,
      docLoading,
      showCreateRequirementDialog,
      editingRequirement,
      uploadDocumentType,
      uploadRef,
      requirementForm,
      getPriorityType,
      getPriorityText,
      getStatusType,
      getStatusText,
      formatDate,
      formatFileSize,
      saveRequirement,
      editRequirement,
      deleteRequirement,
      uploadDocument,
      downloadDocument,
      deleteDocument,
      handleDialogClose
    }
  }
}
</script>

<style scoped>
.project-detail {
  height: 70vh;
  overflow-y: auto;
}

.requirements-section,
.documents-section {
  padding: 20px;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #303133;
}

:deep(.el-tabs__content) {
  height: calc(70vh - 100px);
  overflow-y: auto;
}
</style>
